package com.nashuju.web.controller.role;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.durcframework.core.GridResult;
import org.durcframework.core.JsonObjProcessor;
import org.durcframework.core.MessageResult;
import org.durcframework.core.controller.CrudController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nashuju.web.entity.role.DataPermission;
import com.nashuju.web.entity.role.DataPermissionSch;
import com.nashuju.web.entity.role.Role;
import com.nashuju.web.entity.sys.SysRes;
import com.nashuju.web.service.role.DataPermissionService;
import com.nashuju.web.service.role.RoleService;
import com.nashuju.web.service.sys.SysResService;

@Controller
public class DataPermissionController extends CrudController<DataPermission, DataPermissionService> {

    @Autowired
    private RoleService roleService;
    @Autowired
    private SysResService resService;

    @RequestMapping("/addRDataPermission.do")
    public @ResponseBody MessageResult addRDataPermission(DataPermission entity) {
        SysRes res = resService.get(entity.getSrId());
        if (res == null) {
            return error("资源不存在");
        }
        if (CollectionUtils.isEmpty(entity.getRoleId())) {
            return error("请选择角色");
        }

        this.getService().saveDataPermission(entity);

        return success();
    }

    @RequestMapping("/listRDataPermission.do")
    public @ResponseBody GridResult listRDataPermission(DataPermissionSch searchEntity) {
        return this.queryWithProcessor(searchEntity, new JsonObjProcessor<DataPermission>() {
            @Override
            public void process(DataPermission entity, Map<String, Object> jsonObject) {
                List<Role> roles = roleService.getDataPermissionRole(entity);
                jsonObject.put("roles", roles);
            }
        });
    }

    @RequestMapping("/updateRDataPermission.do")
    public @ResponseBody MessageResult updateRDataPermission(DataPermission entity) {
        SysRes res = resService.get(entity.getSrId());
        if (res == null) {
            return error("资源不存在");
        }
        if (CollectionUtils.isEmpty(entity.getRoleId())) {
            return error("请选择角色");
        }

        this.getService().updateDataPermission(entity);

        return success();
    }

    @RequestMapping("/delRDataPermission.do")
    public @ResponseBody MessageResult delRDataPermission(DataPermission entity) {
        this.getService().delDataPermission(entity);

        return success();
    }

}
